﻿using IT_RoadBlock.Comands;
using IT_RoadBlock.DataContexts;
using IT_RoadBlock.Dto;
using IT_RoadBlock.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace IT_RoadBlock.ViewModes
{
    public class ProjectPageViewModel : ListRelayCommand<TProjectInfo>
    {

        public FyDbContext DbContext = new FyDbContext();

        private string name = "";
        private string projectCode = "";
       

        /// <summary>
        /// 搜索添加
        /// </summary>
        public string Name
        {
            get => name; set
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        public string ProjectCode
        {
            get => projectCode; set
            {
                projectCode = value;
                OnPropertyChanged(nameof(ProjectCode));
            }
        }

        #region SearchCmd
        /// <summary>
        /// 搜索
        /// </summary>
        public override void SearchCmdExecute(TProjectInfo obj)
        {
            DbContext.Database.Log = Console.Write;
            IQueryable<TProjectInfo> queryables1 = DbContext.TProjectInfoDbSet.Where(p => 1 == 1);
            if (!string.IsNullOrEmpty(this.Name))
            {
                queryables1 = queryables1.Where(p => p.Name.Contains(this.Name));
            }
            if (!string.IsNullOrEmpty(this.ProjectCode))
            {
                queryables1 = queryables1.Where(p => p.ProjectCode.Contains(this.ProjectCode));
            }
            int total = queryables1.Count();
            this.DataList = queryables1.OrderBy(p=>p.CreateTime).Skip((this.PageNumber-1)*this.PageSize).Take(this.PageSize).ToList();
            this.PageCount = total % this.PageSize == 0 ? total / this.PageSize : total / this.PageSize + 1;
        }

        public override void RemoveItemsCmdExecute(TProjectInfo obj)
        {
            if (this.DataList?.Any() == true)
            {
                IEnumerable<TProjectInfo> removeItems = this.DataList.Where(p => p._DataSelected);
                if (!removeItems.Any())
                {
                    DialogWindow?.Invoke(this, ResultFactory.Ok("请选择需要删除的数据!"));
                    return;
                }
                DbContext.TProjectInfoDbSet.RemoveRange(removeItems);
                DbContext.SaveChanges();
                SearchCmdExecute(null);
            }
        }
        #endregion




        public ProjectPageViewModel()
        {
            
            SearchCmdExecute(null);
        }

        ~ProjectPageViewModel()
        {
            DbContext?.Dispose();
        }
    }
}
